package service

import (
	"errors"
	"gorm.io/gorm"
	"week1/textrpc/models"
)

// GetTextById todo 根据id获取文章详情
func GetTextById(id int) (*models.Text, error) {
	text := new(models.Text)
	return text, models.InitMysql(func(DB *gorm.DB) error {
		res := DB.Where("id", id).First(&text)
		if res.RowsAffected == 0 {
			return errors.New("数据不存在")
		}
		return nil
	})
}

// GetTextAll todo 根据文章类型  或者 标签 推荐
func GetTextAll(typeId int, tag string) ([]*models.Text, error) {
	var textAll []*models.Text
	return textAll, models.InitMysql(func(DB *gorm.DB) error {
		res := DB.Where("type_id = ?", typeId).Or(DB.Where("tag", tag)).Find(&textAll)
		if res.RowsAffected == 0 {
			return errors.New("无数据")
		}
		return nil
	})
}
func GetWeekDescAll(week string) ([]*models.Text, error) {
	var textAll []*models.Text
	return textAll, models.InitMysql(func(DB *gorm.DB) error {
		res := DB.Where("created_at > ?", week).Order("look_count desc").Limit(10).Find(&textAll)
		if res.RowsAffected == 0 {
			return errors.New("无数据")
		}
		return nil
	})
}
